package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
@Slf4j
public class AddressBookServiceImpl implements AddressBookService {
    @Autowired
    private AddressBookMapper addressBookMapper;

    /**
     * 新增地址
     * @param addressBook
     */
    @Override
    public void saveAddress(AddressBook addressBook) {
        log.info("新增地址:{}",addressBook);
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBook.setIsDefault(0);
        addressBookMapper.insert(addressBook);

    }

    /**
     * 查询用户地址
     * @return
     */
    @Override
    public List<AddressBook> getAddress() {
        Long id = BaseContext.getCurrentId();
        log.info("根据{}查询用户地址",id);
        return  addressBookMapper.getAddress(id);
    }

    /**
     * 根据id查询地址-查询回显
     * @param id
     * @return
     */
    @Override
    public AddressBook getById(Long id) {
        return addressBookMapper.getById(id);
    }

    //修改地址
    @Override
    public void updateAddress(AddressBook addressBook) {
        addressBookMapper.updateAddress(addressBook);
    }

    /**
     * 删除地址
     * @param id
     */
    @Override
    public void deleteAddress(Long id) {
        addressBookMapper.deleteAddress(id);
    }

    /**
     * 设置默认地址
     * @param
     */
    @Override
    public void setDefault(AddressBook addressBook) {
        List<AddressBook> address = addressBookMapper.getAddress(BaseContext.getCurrentId());
        for (AddressBook addressBook1 : address) {
            addressBook1.setIsDefault(0);
            addressBookMapper.updateAddress(addressBook1);
        }
        addressBook.setIsDefault(1);
        addressBookMapper.setDefault(addressBook);
    }

    /**
     * 根据id查询默认地址
     * @return
     */
    @Override
    public AddressBook getDefault() {
        return addressBookMapper.getDefault(BaseContext.getCurrentId());
    }
}
